/**

   master.c
   ========
	
	
**/


/**

   Includes
   --------
	
   - stdlib.h     : malloc, free
   - stdint.h     : standard type (uint8_t ...)
   - stdio.h      : printf
   - uuid.h       : uuid
   - debug.h      : debug helpers
   - net_server.h : net server
   - file.h       : file
   - btree.h      : btree
   - chunksrv.h   : chunk servers
   - heap.h       : heap
   - dc.h         : datacenters
   - llist.h      : linked lists

**/


#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <uuid.h>
#include <debug.h>
#include <net_server.h>
#include "file.h"
#include "btree.h"
#include "chunksrv.h"
#include "heap.h"
#include "dc.h"
#include "llist.h"

/**

   Function: void my_handler(int connFD)
   -------------------------------------

**/

#include <unistd.h>

void my_handler(int connFD)
{
  char buf[2048];
  ssize_t n;

  while ( (n=read(connFD,buf,2048)) )
    {
      buf[n] = 0;
      
      printf("Received: %s",buf);
      
    }
  
  return;
}



/**

   Function: main
   --------------

**/


int main(int argc, char* argv[])
{
  struct b_tree* btree;
  struct huff_tree* htree;
  struct net_server* s;

  htree = huff_create();
  if (htree == NULL)
    {
      goto err0;
    }

  btree = btree_create(file_compare);
  if ( btree == NULL )
    {
      goto err1;
    } 
  
  s = net_create(8080,1024,5,my_handler);
  if (s==NULL)
    {
      fprintf(stderr,"Cannot create server\n");
      goto err2;
    }

  if (net_listen(s) != EXIT_SUCCESS)
    {
      fprintf(stderr,"Cannot listen\n");
      goto err3;
    }
  
  
  if (net_run(s) != EXIT_SUCCESS)
    {
      fprintf(stderr,"Cannot run\n");
      goto err3;
    }

 
  struct file* f;

  f = file_create("toto",htree);
  file_add_chunk(f);
  file_add_chunk(f);
  file_add_chunk(f);
  debug_print_file(f);
  
  file_delete(f);


  /* Do nothing :) */
  while(0)
    {
      pause();
    }

 
  /* Clean up */
  net_delete(s);
  btree_delete(btree);
  huff_delete(htree);
 
  
  return 0;

 err3:
  
  net_delete(s);

 err2:

  btree_delete(btree);

 err1:

  huff_delete(htree);

 err0:
  printf("An error has occurred\n");

  return 1;
}
